// pages/home/home.js
Page({
  data: {
    // 学习进度相关数据
    progress: {
      completed: 0, // 已完成单词数
      total: 50,    // 目标单词数
      percent: 0,   // 百分比
      newWordsTotal: 20, // 新词总数
      reviewWordsTotal: 30 // 复习词总数
    },
    // 连续打卡相关数据
    streak: {
      days: 0,      // 连续打卡天数
      level: 1      // 勋章等级 (1-5)
    },
    // 剩余单词提示
    remainingWords: 50,
    // 待复习单词数量
    reviewWords: 0,
    // 通知消息
    notifications: [
      {
        id: 1,
        type: 'reminder',
        content: '今天还没有完成学习任务哦，抓紧时间吧！',
        time: '10分钟前'
      },
      {
        id: 2,
        type: 'system',
        content: '恭喜你获得"坚持不懈"勋章！',
        time: '昨天'
      }
    ]
  },

  onLoad: function() {
    // 页面加载时加载学习数据
    this.loadData();
    
    // 注册事件监听
    this.setEventListener();
  },

  onShow: function() {
    // 页面显示时刷新数据
    this.loadData();
  },
  
  // 设置事件监听
  setEventListener: function() {
    // 获取页面实例，用于监听事件
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    
    // 监听从学习页面返回的事件
    if (currentPage.getOpenerEventChannel) {
      const eventChannel = currentPage.getOpenerEventChannel();
      // 监听refreshHomeData事件
      eventChannel.on('refreshHomeData', (data) => {
        console.log('接收到学习页面返回的数据', data);
        this.loadData(); // 刷新数据
      });
    }
  },

  // 加载数据
  loadData: function() {
    // 获取今天的日期
    const today = new Date().toISOString().split('T')[0];
    
    // 从本地存储获取今日学习数据
    const dailyProgress = wx.getStorageSync('dailyProgress') || {};
    
    // 优先使用新格式的数据结构
    if (typeof dailyProgress === 'object' && 'todayWords' in dailyProgress) {
      // 新格式数据
      const completed = dailyProgress.todayWords || 0;
      const total = dailyProgress.dailyGoal || 50;
      const reviewCount = dailyProgress.reviewWords || 0;
      const newWordsTarget = dailyProgress.newWordsTarget || 20;
      const reviewWordsTarget = dailyProgress.reviewWordsTarget || 30;
      
      // 更新页面数据
      this.setData({
        'progress.completed': completed,
        'progress.total': total,
        'progress.newWordsTotal': newWordsTarget,
        'progress.reviewWordsTotal': reviewWordsTarget,
        'remainingWords': Math.max(0, newWordsTarget - completed),
        'reviewWords': reviewCount
      });
    } else {
      // 兼容旧格式数据
      const todayProgress = dailyProgress[today] || { completed: 0, total: 50 };
      
      // 从本地存储获取需要复习的单词数量
      const reviewData = wx.getStorageSync('reviewWords') || {};
      const todayReview = reviewData[today] || 0;
      
      // 默认新词占总数的40%，复习词占60%
      const newWordsTarget = Math.round(todayProgress.total * 0.4);
      const reviewWordsTarget = Math.round(todayProgress.total * 0.6);
      
      // 更新页面数据
      this.setData({
        'progress.completed': todayProgress.completed,
        'progress.total': todayProgress.total,
        'progress.newWordsTotal': newWordsTarget,
        'progress.reviewWordsTotal': reviewWordsTarget,
        'remainingWords': Math.max(0, newWordsTarget - todayProgress.completed),
        'reviewWords': todayReview
      });
    }
    
    // 获取全局数据
    const app = getApp();
    const studyData = app.globalData.studyData;
    
    // 获取连续打卡天数
    const streakDays = studyData.streakDays || 0;
    
    // 根据连续打卡天数计算勋章等级
    let level = 1;
    if (streakDays >= 30) level = 5;
    else if (streakDays >= 20) level = 4;
    else if (streakDays >= 10) level = 3;
    else if (streakDays >= 5) level = 2;
    
    this.setData({
      'streak.days': streakDays,
      'streak.level': level
    });
    
    // 计算百分比
    this.calculateProgress();
    
    // 更新通知信息
    this.updateNotifications();
  },

  // 计算学习进度百分比
  calculateProgress: function() {
    const { completed, total } = this.data.progress;
    const percent = total > 0 ? Math.floor((completed / total) * 100) : 0;
    this.setData({
      'progress.percent': percent
    });
  },
  
  // 更新通知信息
  updateNotifications: function() {
    const { remainingWords, reviewWords } = this.data;
    const notifications = [...this.data.notifications];
    
    // 更新或添加提醒通知
    const reminderIndex = notifications.findIndex(n => n.type === 'reminder');
    const now = new Date();
    const timeStr = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
    
    let message = '';
    
    // 根据新词和复习词的状态更新消息内容
    if (remainingWords <= 0 && reviewWords <= 0) {
      // 全部完成
      message = '恭喜！今日的学习任务已全部完成，真棒！';
      
      if (reminderIndex !== -1) {
        notifications[reminderIndex] = {
          id: notifications[reminderIndex].id,
          type: 'success',
          content: message,
          time: '刚刚'
        };
      } else {
        notifications.unshift({
          id: Date.now(),
          type: 'success',
          content: message,
          time: '刚刚'
        });
      }
    } else {
      // 有待学习内容
      if (remainingWords > 0 && reviewWords > 0) {
        message = `今天还有${remainingWords}个新词和${reviewWords}个复习词待学习，加油！`;
      } else if (remainingWords > 0) {
        message = `今天还有${remainingWords}个新词待学习，加油！`;
      } else if (reviewWords > 0) {
        message = `今天有${reviewWords}个单词需要复习，巩固记忆很重要哦！`;
      }
      
      if (reminderIndex !== -1) {
        notifications[reminderIndex] = {
          id: notifications[reminderIndex].id,
          type: 'reminder',
          content: message,
          time: timeStr
        };
      } else {
        notifications.unshift({
          id: Date.now(),
          type: 'reminder',
          content: message,
          time: timeStr
        });
      }
    }
    
    // 限制通知最多显示3条
    while (notifications.length > 3) {
      notifications.pop();
    }
    
    this.setData({ notifications });
  },

  // 开始学习按钮点击事件
  startLearning: function() {
    wx.navigateTo({
      url: '/pages/learn/learn'
    });
  },

  // 查看通知详情
  viewNotification: function(e) {
    const { id } = e.currentTarget.dataset;
    console.log('查看通知', id);
    // 处理通知点击逻辑
  }
}); 